﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using FDFtpSync.Core;
using FDFtpSync.Entities;
using FDFtpSync.Server.Models;
using FDFtpSync.Utils;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration.UserSecrets;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace FDFtpSync.Server.Controllers
{
    /*
     * CreatedOn: 2018-05-23
     * CreatedBy: Jackie Lee(天宇遊龍)
     */
    /// <summary>
    /// 接口Api
    /// </summary>
    [Route("api/[controller]")]
    public class FilesController : Controller
    {
        private IActionResult Success<T>(T result)
        {
            return Json(ApiResult<T>.Success(result));
        }

        private IActionResult Failure(string message)
        {
            return Json(ApiResult.Faliure(message));
        }

        // POST api/<controller>
        [HttpPost]
        public IActionResult Post([FromBody] ServerParam param)
        {
            if (param == null)
            {
                return Failure("请求参数为空");
            }
            if (param.Password != SyncContext.Current.GetSyncConfig<ServerSyncConfig>().ServerConnectPassword)
            {
                return Failure("访问密码错误");
            }

            var serverPath = SyncContext.Current.GetSyncConfig<ServerSyncConfig>().
                ServerPaths.FirstOrDefault(a => a.Name.Equals(param.PathName, StringComparison.OrdinalIgnoreCase));
            if (serverPath == null)
            {
                return Failure("访问服务路径配置不存在");
            }

            if (!Directory.Exists(serverPath.Path))
            {
                return Failure("访问服务路径不存在");
            }

            var result = new List<TransFile>();
            var root = Utils.PathHelper.FormatPath(serverPath.Path);
            //if (param.SyncOwnedModelOnly) // TODO: 同步条件指定逻辑
            //{
            //    //var list = _syncService.GetOwnedModelList();
            //    //if (list.Count == 0)
            //    //{
            //    //    return Failure("访问只存在xxxxx不存在");
            //    //}
            //    //Utils.PathHelper.GetPathInfos(serverPath.Path, root, serverPath.Root, result, list.Select(a => $"/{a}").ToList());
            //}
            //else
            //{
            //    Utils.PathHelper.GetPathInfos(serverPath.Path, root, serverPath.Root, result);
            //}
            Utils.PathHelper.GetPathInfos(serverPath.Path, root, serverPath.Root, result);

            if (result.Count == 0)
            {
                return Failure("访问服务路径为空目录");
            }

            return Success(result);
        }

        [HttpPost]
        [Route("md5")]
        public IActionResult GetFileMd5([FromBody] DownloadParam param)
        {
            if (param == null)
            {
                return Failure("请求参数为空");
            }
            var serverPath =
SyncContext.Current.GetSyncConfig<ServerSyncConfig>().ServerPaths.FirstOrDefault(a =>
a.Name.Equals(param.PathName, StringComparison.OrdinalIgnoreCase));
            if (serverPath == null)
            {
                return Failure("访问服务路径配置不存在");
            }

            var fileName = $"{serverPath.Path}{param.FileName}";
            if (!System.IO.File.Exists(fileName))
            {
                return Failure("访问服务路径配置不存在");
            }

            return Success(MD5Helper.Md5File(fileName));
        }

        // POST api/<controller>
        [HttpPost]
        [Route("download")]
        public IActionResult Download([FromBody] DownloadParam param)
        {
            if (param == null)
            {
                return Failure("请求参数为空");
            }
            var serverPath =
                SyncContext.Current.GetSyncConfig<ServerSyncConfig>().ServerPaths.FirstOrDefault(a =>
                    a.Name.Equals(param.PathName, StringComparison.OrdinalIgnoreCase));
            if (serverPath == null)
            {
                return NotFound(Failure("访问服务路径配置不存在"));
            }

            var fileName = $"{serverPath.Path}{param.FileName}";
            if (!System.IO.File.Exists(fileName))
            {
                return NotFound(Failure("访问服务路径配置不存在"));
            }

            var type = Path.GetExtension(fileName).Equals(".txt", StringComparison.OrdinalIgnoreCase) ? "text/plain" : "application/octet-stream";

            using (var fs = new FileStream(fileName, FileMode.Open))
            {
                var ms = new MemoryStream();
                fs.CopyTo(ms);
                ms.Seek(0, SeekOrigin.Begin);
                return File(ms, type, Path.GetFileName(fileName));
            }
        }
    }
}
